package com.zcckj.demo.app.service;

import com.zcckj.common.mvc.result.Result;
import com.zcckj.common.mvc.result.ResultBuilder;
import com.zcckj.demo.app.client.PayClient;
import com.zcckj.demo.app.model.dto.PlaceOrderDTO;
import com.zcckj.demo.order.model.dto.OrderDTO;
import com.zcckj.demo.order.provider.OrderWriteService;
import com.zcckj.demo.pay.model.dto.ReduceBalanceDTO;
import com.zcckj.demo.storage.model.dto.ReduceStockDTO;
import com.zcckj.demo.storage.provider.StorageWriteService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * <p>
 *  聚合服务
 * </p>
 *
 * @author zhangjie
 * @since 2019-08-28
 */
@SuppressWarnings({"SpringJavaInjectionPointsAutowiringInspection", "Duplicates"})
@Slf4j
@Service
public class BusinessOrderService {

    @Reference(group = "${dubbo.services.group}",version = "${dubbo.services.version}")
    private OrderWriteService orderWriteService;

    /** dubbo与feign混合使用的例子 */
    @Autowired
    private PayClient payClient;

    @Reference(group = "${dubbo.services.group}",version = "${dubbo.services.version}")
    private StorageWriteService storageWriteService;

    @GlobalTransactional(rollbackFor = Exception.class)
    public Result placeOrder(PlaceOrderDTO placeOrderDTO){
        Integer amount = 1;
        Integer price = placeOrderDTO.getPrice();

        OrderDTO orderDTO = OrderDTO.builder()
                .userId(placeOrderDTO.getUserId())
                .productId(placeOrderDTO.getProductId())
                .status(OrderDTO.OrderStatus.INIT)
                .payAmount(price)
                .build();

        Boolean success = orderWriteService.createOrder(orderDTO);
        log.info("保存订单结果:{}", success);
        log.info("当前 XID: {}", RootContext.getXID());
        // 扣减库存
        log.info("开始扣减库存");
        ReduceStockDTO reduceStockDTO = ReduceStockDTO.builder()
                .productId(placeOrderDTO.getProductId())
                .amount(amount)
                .build();
        Boolean reduceStockSuccess = storageWriteService.reduceStock(reduceStockDTO);
        log.info("扣减库存结果:{}", reduceStockSuccess);

        // 扣减余额
        log.info("开始扣减余额");
        ReduceBalanceDTO reduceBalanceDTO = ReduceBalanceDTO.builder()
                .userId(placeOrderDTO.getUserId())
                .price(price)
                .build();

        Boolean reduceBalanceSuccess = payClient.reduceBalance(reduceBalanceDTO);
        log.info("扣减余额结果:{}", reduceBalanceSuccess);

        return ResultBuilder.ok();
    }
}
